package com.qsj.easydarwin.util;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class ImageUtil {
    protected static final Logger logger = LoggerFactory.getLogger(ImageUtil.class);

    /**
     * 图片保存
     */
    public static boolean save(String base64String, String filePath, String fileName) {
        //去掉前面的“data:image/jpeg;base64,”的字样
        String imgdata = base64String.replace("data:image/jpeg;base64,", "")
                .replace("data:image/png;base64,","");

        //解码base64
        byte[] data = Base64.decodeBase64(imgdata);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                data[i] += 256;
            }
        }
        //写入保存成jpeg文件
        FileOutputStream fos = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            fos = new FileOutputStream(String.format("%s/%s", filePath, fileName));
            fos.write(data);
        } catch (Exception e) {
            logger.error("图片保存：失败", e);
            return false;
        } finally {
            try {
                fos.flush();
                fos.close();
            } catch (IOException e) {
                logger.error("图片保存：文件关闭失败", e);
            }
        }

        return true;
    }

    /**
     * 本地图片转base64字符串
     */
    public static String imageToBase64String(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            return null;
        }
        return String.format("data:image/jpeg;base64,%s", Base64.encodeBase64String(data));
    }

    /**
     * 删除照片
     */
    public static boolean deleteImage(String imgPath) {
        boolean result = false;
        File file = new File(imgPath);
        if (file.exists()) {
            file.delete();
            result = true;
            //System.out.println("文件已经被成功删除");
        }
        return result;
    }
}
